import pyaudio
import wave
import threading
from PyQt5 import QtCore


class MyThread (threading.Thread):
    def __init__(self, wave_out_path, button):
        threading.Thread.__init__(self)
        self.wave_out_path = wave_out_path
        self.button = button

    def run(self):
        recordAudio(self.wave_out_path, self.button)
        self.button.setText(QtCore.QCoreApplication.translate("MainWindow", "开始录制"))



CHUNK = 1024  # 每个缓冲区的帧数
FORMAT = pyaudio.paInt16  # 采样位数
CHANNELS = 1  # 单声道
RATE = 44100  # 采样频率
RECORD_SECONDS = 2

def recordAudio(wave_out_path, button):
    """ 录音功能 """
    p = pyaudio.PyAudio()  # 实例化对象
    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)  # 打开流，传入响应参数
    wf = wave.open(wave_out_path, 'wb')  # 打开 wav 文件。
    wf.setnchannels(CHANNELS)  # 声道设置
    wf.setsampwidth(p.get_sample_size(FORMAT))  # 采样位数设置
    wf.setframerate(RATE)  # 采样频率设置

    # while button.keepVoiceInput:
    #     data = stream.read(CHUNK)
    #     wf.writeframes(data)  # 写入数据
    for i in range(int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        wf.writeframes(data)  # 写入数据
    stream.stop_stream()  # 关闭流
    stream.close()
    p.terminate()
    wf.close()